package com.itestmini.testplatformbackend;

import com.alibaba.fastjson2.JSON;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.rpc.service.GenericService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RequestDubboTestV2 {

    /**
     * 发送 Dubbo 请求
     * @param url 请求地址
     * @param dubboApi 请求接口
     * @param dubboMethod 请求方法
     * @param dubboRequestName 请求方法名字
     * @param request 请求体
     * @param newFlag 默认值
     * @param version 版本号
     * @return 响应结果
     * @auth Xiaochun
     */
    public static String send(String url, String dubboApi, String dubboMethod, String dubboRequestName, String request, String newFlag, String version) {
        if (newFlag != "") {
            dubboApi = dubboApi.replaceAll("com.weihui", newFlag);
            dubboMethod = dubboMethod.replaceAll("com.weihui", newFlag);
            dubboRequestName = dubboRequestName.replaceAll("com.weihui", newFlag);
            request = request.replaceAll("com.weihui", newFlag);
        }
        ApplicationConfig application = new ApplicationConfig();
        application.setName("api-test");

        ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>();
        reference.setInterface(dubboApi);
        reference.setGeneric(true);
        reference.setApplication(application);
        reference.setTimeout(30000);
        reference.setRetries(0);
        if (version == null) {
            System.setProperty(dubboApi, url);
        } else {
            System.setProperty(dubboApi, url + "?version=" + version);
        }

        GenericService genericService = reference.get();
        //
        String[] dubboRequestNameArray = dubboRequestName.split("#");
        String[] parameterPackageArray = request.split("#");
        Object[] requestMaps = new Object[parameterPackageArray.length];
        for (int i = 0; i < parameterPackageArray.length; i++) {
            if (parameterPackageArray[i].trim().startsWith("{")) {
                requestMaps[i] = (Map) JSON.parse(parameterPackageArray[i]);
            } else if (parameterPackageArray[i].trim().startsWith("[")) {
                //如果是对象是LIST话
                String trim = parameterPackageArray[i].trim();
                parameterPackageArray[i] = trim.substring(0, trim.length() - 1).substring(1);
                String[] a = parameterPackageArray[i].split("@");
                List list = new ArrayList();
                for (int j = 0; j < a.length; j++) {
                    list.add(JSON.parse(a[j]));
                }
                requestMaps[i] = list;
            } else {
                requestMaps[i] = parameterPackageArray[i].trim();
            }
        }

        // 发送请求
        Object response = genericService.$invoke(dubboMethod, dubboRequestNameArray, requestMaps);
        reference.destroy();
        if (response != null) {
            return response.toString();
        }
        return "dubbo请求返回了空";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 使用线程池执行并发请求
        int numRequests = 1;
        ExecutorService executorService = Executors.newFixedThreadPool(numRequests);

        CompletableFuture<Void>[] futures = new CompletableFuture[numRequests];
        for (int i = 0; i < numRequests; i++) {
            int index = i;
            futures[i] = CompletableFuture.runAsync(() -> {
                String request = "{"
                        + "\"accessChannel\":\"WEB\","
                        + "\"gmtPayExpired\":\"2025-04-02 20:57:01\","
                        + "\"partnerId\":\"200000030903\"," //uat-200000030903   sim-200000030906
                        + "\"tradeVoucherNo\":\"139991743597721551\","
                        + "\"depositSrcVoucherNo\":\"20250402204201\","
                        + "\"gmtSubmit\":\"2025-04-02 20:42:01\","
                        + "\"amount\": {"
                        + "\"amount\": \"1\","
                        + "\"cent\": \"100\","
                        + "\"currency\":\"AED\","
                        + "\"class\": \"com.uaepay.common.util.money.Money\""
                        + "},"
                        + "\"accountType\":\"BASIC\","
                        + "\"class\": \"com.uaepay.deposit.api.domain.request.DepositRequest\","
                        + "\"bizProductCode\":\"230102\","
                        + "\"paymentInfo\": {"
                        + "\"extension\": \"{\\\"INST_CODE\\\":\\\"KIOSK\\\",\\\"payerFromPartnerId\\\":\\\"200000030903\\\"}\","//uat-200000030903   sim-200000030906
                        + "\"payMode\": \"NETBANK\","
                        + "\"class\": \"com.uaepay.deposit.api.domain.PaymentInfo\","
                        + "\"paymentVoucherNo\": \"319991743597721551\","
                        + "\"paymentChannel\": \"18\""
                        + "},"
                        + "\"memberId\": \"100000082380\"" //uat-100000082380   sim-100000327676
                        + "}";

                String operationEnv = "{}"; // 日志中显示 OperationEnvironment 但未提供具体内容，设为空对象

                String response = send(
                        "dubbo://uat.nodeservice.test2pay.com:31018", // uat:   uat.nodeservice.test2pay.com:31018   sim:   sim.nodeservice.test2pay.com:31018
                        "com.uaepay.deposit.api.DepositService", // Dubbo API 接口
                        "deposit", // 方法名称
                        "com.uaepay.deposit.api.domain.request.DepositRequest#com.weihui.common.domain.OperationEnvironment", // 参数类型列表
                        request + "#" + operationEnv, // 参数内容，两个参数以 "#" 连接
                        "com.uaepay", // newFlag 设为默认值
                        "" // 版本号
                );
                System.out.println("Thread ID: " + Thread.currentThread().getId() + " Response: " + response);
            }, executorService);
        }

        // 等待所有并发请求完成
        CompletableFuture.allOf(futures).join();
        executorService.shutdown();
    }

    public static String extractReturnCode(String response) {
        // 查找返回的 returnCode 部分
        int startIndex = response.indexOf("returnCode=");
        if (startIndex != -1) {
            startIndex += "returnCode=".length();  // 移动到值的开始位置
            int endIndex = response.indexOf(",", startIndex); // 查找下一个逗号的位置
            if (endIndex == -1) {
                endIndex = response.indexOf("}", startIndex);  // 如果没有逗号，查找结尾的 }
            }
            return response.substring(startIndex, endIndex).trim();
        }
        return null; // 如果没有找到 returnCode，则返回 null
    }
}
